package com.bzkj.basicinfo.service.impl.ncc;

import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.bzkj.basicinfo.domain.ncc.NccBasicManufacturerInfo;
import com.bzkj.basicinfo.domain.ncc.erp.ManufacturerInfoBean;
import com.bzkj.basicinfo.mapper.NccBasicManufacturerInfoMapper;
import com.bzkj.basicinfo.service.ncc.NccBasicManufacturerInfoService;
import com.bzkj.basicinfo.utils.HttpClientUtils;
import com.bzkj.basicinfo.utils.NccBasicUtil;
import com.bzkj.common.core.domain.AjaxResult;
import com.bzkj.common.core.domain.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 工厂组织信息：9
 */
@Slf4j
@Service("nccJobManufacturerInfoService")
public class NccBasicManufacturerInfoServiceImpl implements NccBasicManufacturerInfoService
{
    @Autowired
    private NccBasicManufacturerInfoMapper nccBasicManufacturerInfoMapper;
    @Autowired
    private NccBasicUtil nccBasicUtil;
    @Value("${ncc.baseUrl}")
    private String url;

    @Value("${ncc.basicInfoUrl}")
    private  String basicInfoUrl;
    @Value("${ncc.sourceSystem}")
    private static String sourceSystem;

    @Value("${ncc.targetSystem}")
    private static String targetSystem;

    @Value("${ncc.serviceName}")
    private static String serviceName;

    @Value("${ncc.contentType}")
    private static String contentType;

    @Value("${pk_org.code}")
    private Integer pkOrgCode;

    @Override
    public void updateNccBasicManufacturerInfoJob(String all)
    {
        if("all".equals(all)) {
            nccBasicUtil.ncc(9, pkOrgCode);
        } else {
            HttpResponse response = methodExecute(9);
            if(response.isOk()) {
                String responseBody = response.body();
                JSONObject entries = JSONUtil.parseObj(responseBody);
                JSONArray dataArray = entries.getJSONArray("data");
                List<NccBasicManufacturerInfo> basicManufacturerInfos = dataArray.toList(NccBasicManufacturerInfo.class);
                for(NccBasicManufacturerInfo basicManufacturerInfo : basicManufacturerInfos) {
                    NccBasicManufacturerInfo basicManufacturerInfo1 = nccBasicManufacturerInfoMapper.queryNccBasicManufacturerInfo(basicManufacturerInfo.getCode());
                    if(basicManufacturerInfo1 != null) {
                        nccBasicManufacturerInfoMapper.updateNccBasicManufacturerInfo(basicManufacturerInfo);
                    } else {
                        nccBasicManufacturerInfoMapper.insertNccBasicManufacturerInfo(basicManufacturerInfo);
                    }
                }
            }
        }
    }

    /**
     * 根据条件分页查询集团企业信息
     *
     * @Author wangzhichao
     * @Date 2024/12/09 14:54:30
     * @Param entity
     */
    @Override
    public List<NccBasicManufacturerInfo> findNccBasicManufacurerInfoData(NccBasicManufacturerInfo entity)
    {
        return nccBasicManufacturerInfoMapper.findNccBasicManufacurerInfoData(entity);
    }

    /**
     * 根据code修改集团信息
     *
     * @Author wangzhichao
     * @Date 2024/12/09 14:58:32
     * @Param entity
     */
    @Override
    public AjaxResult nccBasicManufacurerInfoUpdate(NccBasicManufacturerInfo entity)
    {
        try {
            NccBasicManufacturerInfo info = nccBasicManufacturerInfoMapper.queryNccBasicManufacturerInfo(entity.getCode());
            if(Objects.isNull(info)) {
                nccBasicManufacturerInfoMapper.updateNccBasicManufacturerInfo(entity);
                return AjaxResult.success("修改成功");
            } else {
                if(info.getCode().equals(entity.getCode())) {
                    nccBasicManufacturerInfoMapper.updateNccBasicManufacturerInfo(entity);
                    return AjaxResult.success("修改成功");
                } else {
                    return AjaxResult.error("集团代码重复");
                }
            }
        } catch(Exception e) {
            log.error("修改失败:{}", e);
            return AjaxResult.error("修改失败");
        }
    }

    /**
     * 新增集团信息
     *
     * @Author wangzhichao
     * @Date 2024/12/10 09:03:57
     * @Param entity
     */
    @Override
    public AjaxResult nccBasicManuFacurerInfoSave(NccBasicManufacturerInfo entity)
    {
        try {
            NccBasicManufacturerInfo info = nccBasicManufacturerInfoMapper.queryNccBasicManufacturerInfo(entity.getCode());
            if(Objects.isNull(info)) {
                entity.setpK_ORG("1001A110000000004AOQ");
                nccBasicManufacturerInfoMapper.insertNccBasicManufacturerInfo(entity);
                return AjaxResult.success("新增成功");
            } else {
                return AjaxResult.error("集团信息重复(code)");
            }
        } catch(Exception e) {
            log.error("新增失败:{}", e);
            return AjaxResult.error("新增失败");
        }
    }

    @Override
    public R findBasicManufacturerInfo()
    {
        List<NccBasicManufacturerInfo> list = nccBasicManufacturerInfoMapper.findBasicManufacturerInfo();
        return R.ok(list);
    }

    @Autowired
    private HttpClientUtils hcu;

    @Override
    public R jobMethodExecute()
    {
        LocalDateTime startOfDay = LocalDateTime.now()
                .withHour(0)
                .withMinute(0)
                .withSecond(0)
                .withNano(0);

        LocalDateTime endOfDay = LocalDateTime.now()
                .withHour(23)
                .withMinute(59)
                .withSecond(59)
                .withNano(999_999_999);
        DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String afterTime = endOfDay.format(pattern);
        String beforeTime = startOfDay.format(pattern);
        HttpResponse response = hcu.methodExecute(beforeTime, afterTime, 9, pkOrgCode);
        com.alibaba.fastjson2.JSONObject jsonNode = JSON.parseObject(response.body());
        // 收集rep系统数据
        List<ManufacturerInfoBean> list = jsonNode.getJSONArray("data").toJavaList(ManufacturerInfoBean.class);
        if(! list.isEmpty())
            extracted(list);

        return R.ok("同步成功");
    }

    /**
     * 批量更新或者插入
     *
     * @Date 2024/12/11 14:17:12
     * @Param list
     */
    @Transactional(rollbackFor = Exception.class)
    public void extracted(List<ManufacturerInfoBean> list)
    {
        List<NccBasicManufacturerInfo> collect = list.parallelStream().map(item -> {
            NccBasicManufacturerInfo temp = new NccBasicManufacturerInfo();
            BeanUtils.copyProperties(item, temp);
            return temp;
        }).collect(Collectors.toList());

        //收集主键数据
        List<String> pkMeasdoc = collect.parallelStream().map(NccBasicManufacturerInfo :: getCode).collect(Collectors.toList());
        //查看已经存在的主键
        Set<String> existpkMeasdocSet = nccBasicManufacturerInfoMapper.findNccBasicpkMeasdocSetList(pkMeasdoc);
        //获取需要更新的数据
        collect.parallelStream().filter(item -> existpkMeasdocSet.contains(item.getCode())).forEach(item -> {
            nccBasicManufacturerInfoMapper.updateNccBasicManufacturerInfo(item);
        });
        //需要新增的数据
        collect.parallelStream().filter(item -> ! existpkMeasdocSet.contains(item.getCode())).forEach(item -> {
            nccBasicManufacturerInfoMapper.insertNccBasicManufacturerInfo(item);
        });
    }

    /**
     * 公有方法抽取
     *
     * @param i
     * @return
     */
    public HttpResponse methodExecute(Integer i)
    {
        //        String url = NccHttpUtils.getUrl();
        HashMap<String, Object> hashMap = new HashMap<>();
        // 定义时间格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // 获取昨天的日期
        LocalDate yesterday = LocalDate.now().minusDays(1);
        // 昨天的00:00
        LocalDateTime startOfYesterday = yesterday.atStartOfDay();
        String startOfYesterdayStr = startOfYesterday.format(formatter);
        // 昨天的23:59:59
        LocalDateTime endOfYesterday = yesterday.atTime(23, 59, 59);
        String endOfYesterdayStr = endOfYesterday.format(formatter);
        //        添加post请求参数
        hashMap.put("startTime", startOfYesterdayStr);

        //        hashMap.put("startTime", "2022-01-01 02:32:20");
        hashMap.put("endTime", endOfYesterdayStr);
        hashMap.put("nccBaseDataEnum", i);
        hashMap.put("platformCode", "111");
        String jsonString = JSONUtil.toJsonStr(hashMap);

        // 添加请求头
        HttpResponse response = HttpUtil.createPost(basicInfoUrl).header("sourceSystem", sourceSystem).header("targetSystem", targetSystem).header("serviceName", serviceName).header("contentType", contentType).body(jsonString, "application/json").execute();
        return response;
    }
}
